<?php
class Processor {

	const II_STRETCH = 0;
	const II_PAD = 1;
	const II_CROP = 2;
	const II_PASSTHROUGH = 3;
	const II_FIT = 4;

	const INFO_TYPE_ADDRESS = 1;
	const INFO_TYPE_AWARD = 2;
	const INFO_TYPE_BIOGRAPHY = 3;
	const INFO_TYPE_GENERAL_INFORMATION = 4;
	const INFO_TYPE_PRODUCT = 5;
	const INFO_TYPE_Q_A = 6;
	const INFO_TYPE_RECIPE = 7;
	const INFO_TYPE_SONG = 8;

	private $folderItemTypes = array('image'=>2,'video'=>1);
	public function getFolderItemTypes(){
		return $this->folderItemTypes;
	}
	
	public function __construct() {
		$this->folderTypes = PMSDB3Constants::$folderTypes;
		$this->folderTypes[20] = 'regular';
	}

	public function getValueByLanguagePriority($data, $field) {
		return ($data["{$field}_chinese"]) ? $data["{$field}_chinese"] : $data["{$field}_english"];
	}
	
	public function combineFullName($first_name, $last_name, $language_id) {
		$name = ($language_id == 1) ? "{$last_name}{$first_name}" : "{$first_name} {$last_name}";
		return trim($name);
	}
	
	public function getCastDefaultName($cast) {
		$default_name = '';
		if($cast['first_name'] || $cast['last_name']) {
			if($cast['alphabet'] != 1) {
				$default_name = trim($cast['first_name'].' '.$cast['last_name']);
			}
			else {
				$default_name = trim($cast['last_name'].$cast['first_name']);
			}
		}
		elseif(isset($cast['other_name'])) {
			$default_name = trim($cast['other_name']);
		}
		
		return $default_name;
	}
	
	public function genFolderDataByFolderItemData($item) {
		$data = array(
			'id' => $item['folder_id'],
			'type' => $item['folder_type'],
			'name' => $item['folder_name'],
			'title' => $item['folder_title'],
			'title_chinese' => $item['folder_title_chinese'],
			'title_english' => $item['folder_title_english'],
			'contains' => ($item['item_type'] == 1) ? 'video' : 'image'				
		);
	
		return $data;
	}
	
	public function genFolderItemImageDataByFolderItemDataAndImageData($item, $image) {
		$data = array(
			'id' => $image['id'],
			'programme_id' => $image['programme_id'],
			'ii_id' => $image['ii_id'],
			'title' => $item['title'],
			'title_chinese' => $item['title_chinese'],
			'title_english' => $item['title_english'],
			'subtitle' => '',
			'description' => $item['description'],
			'description_chinese' => $item['description_chinese'],
			'description_english' => $item['description_english'],
			'licenses' => '',
			'modified_at' => $image['modified_at'],
			'online_time' => $image['online_time'],
			'offline_time' => $image['offline_time'],
			'folder_id' => $item['folder_id'],
			'folder_type' => $item['folder_type'],
			'rank' => $item['rank'],
			'time' => $item['time'],
		);

		return $data;
	}
	
	public function genFolderItemVideoDataByFolderItemDataAndVideoData($item, $video) {
		$data = array(
			'id' => $video['id'],
			'programme_id' => $video['programme_id'],
			'episode_id' => $video['episode_id'],
			'vi_id' => $video['vi_id'],
			'image_id' => $video['image_id'],
			'title' => $item['title'],
			'title_chinese' => $item['title_chinese'],
			'title_english' => $item['title_english'],
			'subtitle' =>$video['subtitle'],
			'description' => $item['description'],
			'description_chinese' => $item['description_chinese'],
			'description_english' => $item['description_english'],
			'other_videoes' => $video['other_videoes'],
			'breakpoint' => $video['breakpoint'],
			'duration' => $video['duration'],
			'online_time' => $video['online_time'],
			'offline_time' => $video['offline_time'],
			'tags' => $video['tags'],
			'country_allow_list' => $video['country_allow_list'],
			'country_deny_list' => $video['country_deny_list'],
			'folder_id' => $item['folder_id'],
			'folder_type' => $item['folder_type'],
			'rank' => $item['rank'],
			'time' => $item['time'],
		);
		return $data;
	}
	
	public function convertCastsToCSV($casts) {
		if(!is_array($casts)) {
			return '';
		}
		$csvArr = array();
		foreach($casts as $cast) {
			$default_name = $this->getCastDefaultName($cast);
			if ($default_name) {
				$csvArr[] = $default_name;
			}		
		}

		return implode(',',$csvArr);
	}
	
	public function convertCastsToArray($casts) {
		if(!is_array($casts)) {
			return '';
		}
		$cast_list = array();
		$role_list = PDESGetCastRolePathList();
		foreach ($casts as $type => $type_casts) {
			foreach($type_casts as $cast) {
				$default_name = $this->getCastDefaultName($cast);
				if ($default_name) {
					if (!isset($cast['cast_id'])) {
						$cast['cast_id'] = 0;
					}
					$cast['default_name'] = $default_name;
					$cast_list[$role_list[$type]][] = $cast;
				}
			}
		}

		return $cast_list;
	}

	public function convertTagsFromIdToString($tags) {
		$tags = $this->convertTagsFromIdToHash($tags);
		if(count($tags) == 0) {
			return '';
		}

		foreach($tags as $typeId=>$tags1) {
			$processedTags[$typeId] = implode(',',$tags1);
		}
		return implode(',',$processedTags);
	}

	public function convertTagsFromIdToHash($tags) {
		if(!$tags) {
			return array();
		}

		$tagTypes = PMSDB3Constants::$tagTypes;
		$tags = explode(',',$tags);
		$processedTags = array();
		foreach($tags as $tagId) {
			$tag = PDESGetTagById($tagId);
			if ($tag['tag_type_id'] > 0) {
				$processedTags[$tagTypes[$tag['tag_type_id']]][] = $tag['system_label'];
			}
		}
		return $processedTags;
	}

	public function getProgrammeForPublish($programmeId) {
		$programme = PDESGetProgrammeById($programmeId);

		if($programme === FALSE) return FALSE;

		$programmeFolderList = PDESGetAllFolderListByFolderIds($programme['folders']);

		$episodeFolderList = array();

		$folderList = $programmeFolderList;
		$folderTypes = $this->folderTypes;

		$folders = array();

		$i = 0;
		foreach($folderList as $id=>$folder) {
			$folders[$i] = array(
				'name' => $this->getValueByLanguagePriority($folder, 'title'),
				'title' => $this->getValueByLanguagePriority($folder, 'title'),
				'title_chinese' => $folder['title_chinese'],
				'title_english' => $folder['title_english'],
				'type' => $this->folderTypes[$folder['folder_type_id']],
				'typeId' => $folder['folder_type_id'],
				'contains' => $folder['folder_item_type_id'] == 1 ? 'video' : 'image',
				'id' => $folder['id'],
			);
			$i++;
		}

		$filledFolders = $this->getFoldersForPublish($programmeId,$folders);

		$casts = json_decode($programme['casts'],1);
		$castRoles = PDESGetCastRoles();

		$formattedCasts = array();
		foreach($casts as $type=>$typeCasts) {
			 $formattedCasts[$castRoles[$type]['path']] =
			 	$this->convertCastsToCSV($typeCasts);
		}

		$tags = $this->convertTagsFromIdToHash($programme['tags']);
		$tags['programme_title'] = $programme['title_chinese'];

		if ( (empty($programme['first_episode_time_onair'])) || ($programme['first_episode_time_onair'] == '0000-00-00 00:00:00') ) {
			$programme['first_episode_time_onair'] = '1970-01-01 00:00:00';
		}

		if ( (empty($programme['last_episode_time_onair'])) || ($programme['last_episode_time_onair'] == '0000-00-00 00:00:00') ) {
			$programme['last_episode_time_onair'] = '2029-12-31 23:59:59';
		}

		$banner_keyart_data = PDESGetProgrammeIiId($programme['folders']);
		$programmeNew = array(
			'id' => $programmeId,
			'cpl_id' => $programme['cpl_id'],
			'cpl_company_code' => $programme['cpl_company_code'],
			'cloned_from' => PDESGetClonedFrom($programmeId),
			'name_settop_box_chinese' => $programme['settop_box_name_chinese'],
			'name_settop_box_english' => $programme['settop_box_name_english'],
			'name_chinese' => $programme['title_chinese'],
			'name_english' => $programme['title_english'],
			'description' => $this->getValueByLanguagePriority($programme, 'description'),
			'description_chinese' => $programme['description_chinese'],
			'description_english' => $programme['description_english'],
			'meta_keywords' => $programme['meta_keywords'],
			'meta_description' => $programme['meta_description'],
			'forum_id' => $programme['forum_id'],
			'number_of_episodes' => $programme['number_of_episodes'],
			'executive' => $this->convertCastsToCSV(@$casts[10]),
			'supervisor' => $this->convertCastsToCSV(@$casts[12]),
			'main_actors' => $this->convertCastsToCSV(@$casts[1]),
			'hosts' => $this->convertCastsToCSV(@$casts[3]),
			'guests' => $this->convertCastsToCSV(@$casts[5]),
			'casts' => $formattedCasts,
			'raw_casts' => $this->convertCastsToArray($casts),
			'minisite_url' => $programme['minisite_url'],
			'time_onair' => $programme['first_time_onair'],
			'first_episode_time_onair' => $programme['first_episode_time_onair'],
			'last_episode_time_onair' => $programme['last_episode_time_onair'],
			'banner_image' => isset($banner_keyart_data['banner_image'][0]) ? $banner_keyart_data['banner_image'][0] : '' ,//'NEW FLOW', //$bannerImageProfiles, // Check PP, need to be deprecated
			'key_art_image' => $banner_keyart_data['key_art_image'],//'NEW FLOW', //$keyArtProfiles, // Check PP, need to be deprecated
			'folders' => $filledFolders,
			'tags' => $tags,
			'created_at' => $programme['created_at'],
			'modified_at' => $programme['modified_at'],
			'path' => $programme['path'],
			'objective' => $programme['objective_chinese'],
			'description_short' => $this->getValueByLanguagePriority($programme, 'description_short'),
			'description_short_chinese' => $programme['description_short_chinese'],
			'description_short_english' => $programme['description_short_english'],			
			'story_board' => '',
			'story_board_short' => '',
			'series' => $programme['series_id'],
			'starting_episode_no' => $programme['starting_original_episode_no'],
			'nominal_duration' => $programme['nominal_duration'],
			'first_network_code' => $programme['first_network_codes'],
			'production_start_date' => $programme['production_start_date'],
			'rating' => '',
			'awards' => '',
			'location' => '',
			'location_type' => '',
			'sponsor_name_chinese' => '',
			'sponsor_name_english' => '',
			'umbrella_title_chinese' => '',
			'umbrella_title_english' => '',
			'licenses' => '',
			'blog_url' => $programme['blog_url'],
			'primary_category_id' => $programme['primary_category_id'],
			'channelInfoPremiere' => $this->getValueByLanguagePriority($programme, 'first_onair_information'),
			'channelInfoPremiere_chinese' => $programme['first_onair_information_chinese'],
			'channelInfoPremiere_english' => $programme['first_onair_information_english'],			
			'channelInfoRerun' => '',
			# append by vanni 
			'fact_background'                => $this->getValueByLanguagePriority($programme,'fact_background'),
			'fact_background_chinese'        => $programme['fact_background_chinese'],
			'fact_background_english'        => $programme['fact_background_english'],
			# end
			'online_time' => $programme['publish_datetime'],
			'offline_time' => $programme['expire_datetime'],
		);

		return $programmeNew;
	}

	public function getCastForPublish($castId) {
		$cast = PDESGetCastById($castId);

		if ($cast === FALSE) {
			return FALSE;
		}
		$programme = PDESGetProgrammeById($cast['programme_id']);

		$folderList = PDESGetAllFolderListByFolderIds($cast['folders']);
		$folderTypes = $this->folderTypes;

		$folders = array();

		foreach($folderList as $id=>$folder) {
			$folders[] = array(
				'name' => $this->getValueByLanguagePriority($folder, 'title'),
				'title' => $this->getValueByLanguagePriority($folder, 'title'),
				'title_chinese' => $folder['title_chinese'],
				'title_english' => $folder['title_english'],
				'type' => $folderTypes[$folder['folder_type_id']],
				'typeId' => $folder['folder_type_id'],
				'contains' => $folder['folder_item_type_id'] == 1 ? 'video' : 'image',
				'id' => $folder['id'],
			);
		}

		$filledFolders = $this->getFoldersForPublish($cast['programme_id'],$folders);

		$cast['real_name_chinese'] = $this->combineFullName($cast['real_first_name_chinese'], $cast['real_last_name_chinese'], 1);
		$cast['real_name_english'] = $this->combineFullName($cast['real_first_name_english'], $cast['real_last_name_english'], 2);
		$cast['fake_name_chinese'] = $this->combineFullName($cast['first_name_chinese'], $cast['last_name_chinese'], 1);
		$cast['fake_name_english'] = $this->combineFullName($cast['first_name_english'], $cast['last_name_english'], 2);
		
		$realName = $this->getValueByLanguagePriority($cast, 'real_name');
		$otherName = $this->getValueByLanguagePriority($cast, 'other_name');
		
		$head_full_data = PDESGetCastIiId($cast['folders']);
		$castNew = array(
			'id'=>$castId,
			'programme_id'=>$cast['programme_id'],
			# append by vanni
			'cast_role_id'            => $cast['cast_role_id'],
			'real_first_name'         => $this->getValueByLanguagePriority($cast,'real_first_name'),
			'real_first_name_chinese' => $cast['real_first_name_chinese'],
			'real_first_name_english' => $cast['real_first_name_english'],
			'real_last_name'          => $this->getValueByLanguagePriority($cast,'real_last_name'),
			'real_last_name_chinese'  => $cast['real_last_name_chinese'],
			'real_last_name_english'  => $cast['real_last_name_english'],
			#end
			'real_name'=> ($realName) ? $realName : $otherName,
			'real_name_chinese'=>$cast['real_name_chinese'],
			'real_name_english'=>$cast['real_name_english'],
			'fake_name'=> $this->getValueByLanguagePriority($cast, 'fake_name'),
			'fake_name_chinese'=>$cast['fake_name_chinese'],
			'fake_name_english'=>$cast['fake_name_english'],
			'nickname'=>$this->getValueByLanguagePriority($cast, 'nickname'),
			'nickname_chinese'=>$cast['nickname_chinese'],
			'nickname_english'=>$cast['nickname_english'],
			'gender'=>$cast['gender'],
			'age'=>$cast['age'],
			'occupation'=>$this->getValueByLanguagePriority($cast, 'occupation'),
			'occupation_chinese'=>$cast['occupation_chinese'],
			'occupation_english'=>$cast['occupation_english'],
			'personality'=>$this->getValueByLanguagePriority($cast, 'personality'),
			'personality_chinese'=>$cast['personality_chinese'],			
			'personality_english'=>$cast['personality_english'],
			'profile'=>$this->getValueByLanguagePriority($cast, 'profile'),
			'profile_chinese'=>$cast['profile_chinese'],
			'profile_english'=>$cast['profile_english'],
			'history'=>$this->getValueByLanguagePriority($cast, 'history'),
			'history_chinese'=>$cast['history_chinese'],
			'history_english'=>$cast['history_english'],
			'folders' => $filledFolders,
			'tags'=>$this->convertTagsFromIdToHash($cast['tags']),
			'created_at' => $cast['created_at'],
			'modified_at' => $cast['modified_at'],
			'head_image' => isset($head_full_data['head_image'][0]) ? $head_full_data['head_image'][0] : '',//'NEW FLOW', //$headImageProfiles, for new flow
			'full_body_image' => isset($head_full_data['full_body_image'][0]) ? $head_full_data['full_body_image'][0] : '',//'NEW FLOW',//$fullImageProfiles, for new flow
			'other_image' => array(),
			'blogUrl' => $cast['blog_url'],
			'online_time' => $programme['publish_datetime'],
			'offline_time' => $programme['expire_datetime'],
		);

		return $castNew;
	}

	public function getEpisodeForPublish($episodeId) {
		$episode = PDESGetEpisodeById($episodeId);
		if ($episode === FALSE) {
			return FALSE;
		}

		$programme = PDESGetProgrammeById($episode['programme_id']);

		// Image Folder
		$folderList = PDESGetAllFolderListByFolderIds($episode['folders']);
		$folderTypes = $this->folderTypes;

		$folders = array();

		foreach($folderList as $id=>$folder) {
			$folders[] = array(
				'name' => $this->getValueByLanguagePriority($folder, 'title'),
				'title' => $this->getValueByLanguagePriority($folder, 'title'),
				'title_chinese' => $folder['title_chinese'],
				'title_english' => $folder['title_english'],
				'type' => $folderTypes[$folder['folder_type_id']],
				'typeId' => $folder['folder_type_id'],
				'contains' => $folder['folder_item_type_id'] == 1 ? 'video' : 'image',
				'id' => $folder['id'],
			);
		}

		$filledFolders = $this->getFoldersForPublish($episode['programme_id'],$folders);

		$casts = is_array(json_decode($episode['casts'],1)) ? json_decode($episode['casts'],1) : array();
		$castRoles = PDESGetCastRoles();

		$formattedCasts = array();
		foreach($casts as $type=>$typeCasts) {
			 $formattedCasts[$castRoles[$type]['path']] =
			 	$this->convertCastsToCSV($typeCasts);
		}

		if (is_array($episode['other_language_episodes'])) {
			$other_language_episodes = $episode['other_language_episodes'];
		} elseif ($episode['other_language_episodes'] > 0) {
			$other_language_episodes = array($episode['other_language_episodes']);
		} else {
			$other_language_episodes = array();		
		}
		
		$episodeNew = array(
			'id' => $episodeId,
			'programme_id' => $episode['programme_id'],
			'episode_number' => $episode['onair_episode_no'],
			'title'=>$this->getValueByLanguagePriority($episode, 'title'),
			'title_chinese' => $episode['title_chinese'],
			'title_english' => $episode['title_english'],			
			'subtitle' => '',			
			'description'=>$this->getValueByLanguagePriority($episode, 'description'),
			'description_chinese' => $episode['description_chinese'],
			'description_english' => $episode['description_english'],			
			'personage' => '',
			'main_actors' => $this->convertCastsToCSV(@$casts[1]),
			'hosts' => $this->convertCastsToCSV(@$casts[3]),
			'guests' => $this->convertCastsToCSV(@$casts[5]),
			'casts' => $formattedCasts,
			'raw_casts' => $this->convertCastsToArray($casts),
			'editor' => $this->convertCastsToCSV(@$casts[14]),
			'editor_message'=>$this->getValueByLanguagePriority($episode, 'editor_message'),
			'editor_message_chinese' => $episode['editor_message_chinese'],
			'editor_message_english' => $episode['editor_message_english'],
			'supervisor' => $this->convertCastsToCSV(@$casts[12]),
			'time_onair' => $episode['first_time_onair'],
			'folders' => $filledFolders,
			'tags' => array('programme_title'=>$programme['title_chinese']),
			'created_at' => $episode['created_at'],
			'modified_at' => $episode['modified_at'],
			'description_short'=>$this->getValueByLanguagePriority($episode, 'description_short'),
			'description_short_chinese' => $episode['description_short_chinese'],
			'description_short_english' => $episode['description_short_english'],
			'location' => '',
			'location_type' => '',
			'sponsor_name_chinese' => '',
			'sponsor_name_english' => '',
			'original_episode_no' => $episode['original_episode_no'],
			'rating' => $episode['average_rating'],
			'licenses' => '',
			'other_language_episodes' => $other_language_episodes,
			'online_time' => $episode['publish_datetime'],
			'offline_time' => $episode['expire_datetime'],			
		);

		return $episodeNew;
	}

	public function getChapterForPublish($chapterId) {
		$chapter = PDESGetChapterById($chapterId);
		if ($chapter === FALSE) {
			return FALSE;
		}

		$video = PDESGetVideoById($chapter['video_id']);

		$tags = $this->convertTagsFromIdToHash($chapter['tags']);
		$tags['person'] = array();
		if (isset($chapter['casts'])) {
			$casts = @json_decode($chapter['casts'], TRUE);
			if (is_array($casts)) {
				// Old Format
				$tags['person'] = explode(',',$this->convertCastsToCSV(array_pop($casts)));
			} else {
				// New Format
				$cast_dictionary_ids = explode(",", $chapter['casts']);
				foreach ($cast_dictionary_ids as $cast_dictionary_id) {				
					$cast_dictionary = PDESGetCastDictionaryById($cast_dictionary_id);
					if (isset($cast_dictionary['master'])) {
						$tags['person'][] = $cast_dictionary['master'];
					}
				}
			}
		}

		$categories = PDESGetChapterCategoriesByChapterId($chapterId);
		$category_json = (is_array($categories)) ? json_encode(array_keys($categories)) : json_encode(array());

		$chapterNew = array(
			'id'=>$chapterId,
			'programme_id'=>$video['programme_id'],
			'episode_id' => $video['episode_id'],
			'video_id' => $chapter['video_id'],
			'image_id' => $chapter['ii_id'],//'NEW FLOW', //$profile, for new flow
			'title'=>$this->getValueByLanguagePriority($chapter, 'title'),
			'title_chinese' => $chapter['title_chinese'],
			'title_english' => $chapter['title_english'],
			'subtitle' => '',
			'description'=>$this->getValueByLanguagePriority($chapter, 'description'),
			'description_chinese' => $chapter['description_chinese'],
			'description_english' => $chapter['description_english'],
			'folders' => array(),
			'tags' => $tags,
			'casts' => $tags['person'],
			'created_at' => $chapter['created_at'],
			'modified_at' => $chapter['modified_at'],
			'location' => '',
			'location_type' => '',
			'licenses' => '',
			'in_time' => $chapter['in_time'],
			'out_time' => $chapter['out_time'],
			'infos' => $chapter['infos'],
			'online_time' => $video['publish_datetime'],
			'offline_time' => $video['expire_datetime'],
			'categories' => $category_json
		);

		return $chapterNew;
	}

	public function formatDefaultInfoData($info,$infoType,$extras,$chapterId=0) {
		$info = array(
			'info_id' => $info['id'],
			'episode_id' => $info['episode_id'],
			'info_type_id' => $infoType,
			'extras' => $extras,
			'online_time' => $info['publish_datetime'],
			'offline_time' => $info['expire_datetime'],
			'created_at' => $info['created_at'],
			'modified_at' => $info['modified_at'],
		);

		return $info;
	}

	public function formatCountrySystemLabel($label) {
		return trim(strrchr($label,' '));
	}

	public function getInfoAddressForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoAddressById($infoId);

		$countries = PDESGetCountryList();
		$provinces = PDESGetProvinceList();

		$province = isset($info['province_state_prefecture']) ? $this->formatCountrySystemLabel($provinces[$info['province_state_prefecture']]['system_label']) : '';
		$country = (isset($info['country']) && $info['country'] > 0) ? $this->formatCountrySystemLabel($countries[$info['country']]['system_label']) : '';

        $contact_person = is_array(json_decode($info['contact_person'],1)) ? json_decode($info['contact_person'],1) : array();
		$extras = array(
			'venue_name_chinese' => $info['venue_name_chinese'].'',
			'venue_name_english' => $info['venue_name_english'].'',
			'venue_category' => InfoData::$venue_category[$info['venue_category']].'',
			'street_line_1' => $info['street_line_1'].'',
			'street_line_2' => $info['street_line_2'].'',
			'city' => $info['city'].'',
			'province_state_prefecture' => $province,
			'country' => $country,
			'phone_number' => $info['phone_number'].'',
			'fax_number' => $info['fax_number'].'',
			'url' => $info['url'].'',
			'email' => $info['email'].'',
			'contact_person' => $this->convertCastsToCSV(array_shift($contact_person)),
			'useful_information' => $info['useful_information'].'',
			'description' => $info['description'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_ADDRESS,$extras,$chapterId);
	}

	public function getInfoAwardForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoAwardById($infoId);
        
        $winners = is_array(json_decode($info['winners'],1)) ? json_decode($info['winners'],1) : array();
        $award_presenters = is_array(json_decode($info['award_presenters'],1)) ? json_decode($info['award_presenters'],1) : array();
        $nominees = is_array(json_decode($info['nominees'],1)) ? json_decode($info['nominees'],1) : array();
        $organizations = is_array(json_decode($info['organizations'],1)) ? json_decode($info['organizations'],1) : array();
		$extras = array(
			'award_title_chinese' => $info['award_title_chinese'].'',
			'award_title_english' => $info['award_title_english'].'',
			'award_type' => $info['award_type'].'',
			'winners' => $this->convertCastsToCSV(array_shift($winners)),
			'year' => $info['year'].'',
			'description' => $info['description'].'',
			'award_presenters' => $this->convertCastsToCSV(array_shift($award_presenters)),
			'nominees' => $this->convertCastsToCSV(array_shift($nominees)),
			'organizations' => $this->convertCastsToCSV(array_shift($organizations)),
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_AWARD,$extras,$chapterId);
	}

	public function getInfoBiographyForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoBiographyById($infoId);
		$countries = PDESGetCountryList();
		$provinces = PDESGetProvinceList();

        $province_label = isset($provinces[$info['origin_province_state_prefecture']]['system_label']) ? 
            $provinces[$info['origin_province_state_prefecture']]['system_label'] : '';
        $country_label = isset($countries[$info['origin_country']]['system_label']) ? 
            $countries[$info['origin_country']]['system_label'] : '';

        $province = isset($info['origin_province_state_prefecture']) ? $this->formatCountrySystemLabel($province_label) : '';
        $country = isset($info['origin_country']) ? $this->formatCountrySystemLabel($country_label) : '';

        //$province = isset($info['origin_province_state_prefecture']) ? @$this->formatCountrySystemLabel($provinces[$info['origin_province_state_prefecture']]['system_label']) : '';
		//$country = isset($info['origin_country']) ? @$this->formatCountrySystemLabel($countries[$info['origin_country']]['system_label']) : '';
		$extras = array(
			'name_chinese' => $info['name_chinese'].'',
			'name_english' => $info['name_english'].'',
			'nickname' => $info['nickname'].'',
			'gender' => $info['gender'] == 2 ? 'F' : 'M',
			'date_of_birth_year' => $info['date_of_birth_year'].'',
			'date_of_birth_month' => $info['date_of_birth_month'].'',
			'date_of_birth_day' => $info['date_of_birth_day'].'',
			'origin_country' => $country.'',
			'origin_province_state_prefecture' => $province.'',
			'origin_city' => $info['origin_city'].'',
			'occupation' => $info['occupation'].'',
			'description' => $info['description'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_BIOGRAPHY,$extras,$chapterId);
	}

	public function getInfoGeneralForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoGeneralById($infoId);

		$extras = array(
			'title_chinese' => $info['title_chinese'].'',
			'title_english' => $info['title_english'].'',
			'type' => $info['type'].'',
			'description' => $info['description'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_GENERAL_INFORMATION,$extras,$chapterId);
	}

	public function getInfoProductForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoProductById($infoId);

		$extras = array(
			'product_name_chinese' => $info['product_name_chinese'].'',
			'product_name_english' => $info['product_name_english'].'',
			'brand' => $info['brand'].'',
			'industry' => InfoData::$product_industry[$info['industry']].'',
			'description' => $info['description'].'',
			'url' => $info['url'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_PRODUCT,$extras,$chapterId);
	}

	public function getInfoQAForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoQAById($infoId);

		$extras = array(
			'question' => $info['question'].'',
			'answer' => $info['answer'].'',
			'reference' => $info['reference'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_Q_A,$extras,$chapterId);
	}

	public function getInfoRecipeForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoRecipeById($infoId);

        $designed_by = is_array(json_decode($info['designed_by'],true)) ? json_decode($info['designed_by'],true) : array();
        $presented_by = is_array(json_decode($info['presented_by'],true)) ? json_decode($info['presented_by'],true) : array();
		$extras = array(
			'dish_name_chinese' => $info['dish_name_chinese'].'',
			'dish_name_english' => $info['dish_name_english'].'',
			'cuisine_category' => $info['cuisine_category']>0 ? InfoData::$cuisine_category[$info['cuisine_category']] : '',
			'cuisine_sub_category' => @InfoData::$cuisine_sub_category[$info['cuisine_category']][$info['cuisine_sub_category']].'',
			'food_category' => InfoData::$food_category[$info['food_category']].'',
			'method_type' => InfoData::$food_method_type[$info['method_type']].'',
			'main_ingredients' => InfoData::$food_ingredients[$info['main_ingredients']].'',
			'ingredients' => $info['ingredients'].'',
			'seasonings' => $info['seasonings'].'',
			'cooking_method' => $info['cooking_method'].'',
			'designed_by' => $this->convertCastsToCSV(array_shift($designed_by)),
			'presented_by' => $this->convertCastsToCSV(array_shift($presented_by)),
			'purpose' => $info['purpose'].'',
			'useful_information' => $info['useful_information'].'',
			'description' => $info['description'].'',
			'sauce' => $info['sauce'].'',
			'hints' => $info['hints'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_RECIPE,$extras,$chapterId);
	}

	public function getInfoSongForPublish($infoId,$chapterId=0) {
		$info = PDESGetInfoSongById($infoId);

        $owners = is_array(json_decode($info['owners'],true)) ? json_decode($info['owners'],true) : array(); 
        $singers = is_array(json_decode($info['singers'],true)) ? json_decode($info['singers'],true) : array();
        $group_names = is_array(json_decode($info['group_names'],true)) ? json_decode($info['group_names'],true) : array();
        $producers = is_array(json_decode($info['producers'],true)) ? json_decode($info['producers'],true) : array();
        $composers = is_array(json_decode($info['composers'],true)) ? json_decode($info['composers'],true) : array();
        $lyricists = is_array(json_decode($info['lyricists'],true)) ? json_decode($info['lyricists'],true) : array();
        $arrangers = is_array(json_decode($info['arrangers'],true)) ? json_decode($info['arrangers'],true) : array();
		$extras = array(
			'title_chinese' => $info['title_chinese'],
			'title_english' => $info['title_english'],
			'genre' => isset(InfoData::$song_genre[$info['genre']]) ? InfoData::$song_genre[$info['genre']] : '',
			'singers' => $this->convertCastsToCSV(array_shift($singers)),
			'group_names' => $this->convertCastsToCSV(array_shift($group_names)),
			'producers' => $this->convertCastsToCSV(array_shift($producers)),
			'composers' => $this->convertCastsToCSV(array_shift($composers)),
			'lyricists' => $this->convertCastsToCSV(array_shift($lyricists)),
			'arrangers' => $this->convertCastsToCSV(array_shift($arrangers)),
			'record_company' => $info['record_company'].'',
			'year' => $info['year'].'',
			'lyrics' => $info['lyrics'].'',
			'owners' => $this->convertCastsToCSV(array_shift($owners)),
			'description' => $info['description'].'',
		);

		return $this->formatDefaultInfoData($info,self::INFO_TYPE_SONG,$extras,$chapterId);
	}

	public function getImageForPublish($imageId, $type) {
		if($imageId == 0) return FALSE;

		$image = PDESGetImageById($imageId);
		if($image === FALSE) return FALSE;

		$tags = $this->convertTagsFromIdToHash($image['tags']);

		// New Format
		$tags['person'] = array();
		$cast_dictionary_ids = explode(",", $image['casts']);
		foreach ($cast_dictionary_ids as $cast_dictionary_id) {				
			$cast_dictionary = PDESGetCastDictionaryById($cast_dictionary_id);
			if (isset($cast_dictionary['master'])) {
				$tags['person'][] = $cast_dictionary['master'];
			}
		}
		
		$imagesNew = array(
				'id' => $imageId,
				'programme_id' => $image['programme_id'],
				'ii_id' => $image['ii_id'],//'NEW FLOW', // $profiles, for new flow 
				'title'=>$this->getValueByLanguagePriority($image, 'title'),
				'title_chinese' => $image['title_chinese'],
				'title_english' => $image['title_english'],
				'subtitle' => '', //Not available in PDES?
				'description'=>$this->getValueByLanguagePriority($image, 'description'),
				'description_chinese' => $image['description_chinese'],
				'description_english' => $image['description_english'],
				'licenses' => '',
				'modified_at' => $image['modified_at'],
				'online_time' => $image['publish_datetime'],
				'offline_time' => $image['expire_datetime'],
				'tags' => $tags,
				'created_at' => $image['created_at'],
		);

		return $imagesNew;
	}
	
	public function getVideoForPublish($videoId, $distribute=TRUE) {
        $video = PDESGetVideoById($videoId);
		if($video == FALSE) { return FALSE; }

		$countryAllowList = explode(',',str_ireplace('all','ALL',$video['country_allow_list']));
		$video['country_allow'] = $countryAllowList;
		$countryDenyList = explode(',',str_ireplace('all','ALL',$video['country_deny_list']));
		$video['country_deny'] = $countryDenyList;

		$tags = $this->convertTagsFromIdToHash($video['tags']);

		if (is_array($video['other_videos'])) {
			$other_videos = $video['other_videos'];
		} elseif ($video['other_videos'] > 0) {
			$other_videos = array($video['other_videos']);
		} else {
			$other_videos = array();
		}

		$videoNew = array(
			'id' => $videoId,
			'programme_id' => $video['programme_id'],
			'episode_id' => $video['episode_id'],
			'vi_id' => $video['vi_id'],//'NEW FLOW',    //$videoProfiles, for new flow
			'image_id' => $video['ii_id'],//'NEW FLOW', //$imageProfiles, for new flow 
			'title'=>$this->getValueByLanguagePriority($video, 'title'),
			'title_chinese' => $video['title_chinese'],
			'title_english' => $video['title_english'],
			'subtitle' => json_encode(array('zh-Hant-HK'=>$video['subtitle_cn'],'en-HK'=>$video['subtitle_en'])),//bug 5441
			'description'=>$this->getValueByLanguagePriority($video, 'description'),
			'description_chinese' => $video['description_chinese'],
			'description_english' => $video['description_english'],
			'other_videoes' => $other_videos, // Spelling mistake in PMS WS
			'duration' => 'NEW FLOW', //$source['duration'],
			'breakpoint' => 'NEW FLOW', //$breakpoint_string,
			'online_time' => $video['publish_datetime'],
			'offline_time' => $video['expire_datetime'],
			'country_allow_list' => $video['country_allow_list'],
			'country_deny_list' => $video['country_deny_list'],
			# append by vanni 
			'source_id'						 => $video['source_id'],
			# end
			'tags' => $tags,
			'created_at' => $video['created_at'],
			'modified_at' => $video['modified_at'],
		);
		return $videoNew;
	}

	public function getFoldersForPublish($programmeId,$folders) {
		if (count($folders) == 0) {
			return array();
		}

		$newFolders = array();
		foreach ($folders as $k => $folder) {

			if (count($folder) == 0) {
				continue;
			}

			$itemType = $this->folderItemTypes[$folder['contains']];
			$folderItem = array(
				'folder_id' => $folder['id'],
				'folder_name' => $this->getValueByLanguagePriority($folder, 'title'),
				'folder_title' => $this->getValueByLanguagePriority($folder, 'title'),
				'folder_title_chinese' => $folder['title_chinese'],
				'folder_title_english' => $folder['title_english'],
				'folder_type' => $folder['type'],
				'programme_id' => $programmeId,
				'item_type' => $itemType,
			);

			$items = array();

			$folderItems = PDESGetFolderItemListByFolderId($folder['id']);

			if(count($folderItems) == 0) {
				continue;
			}

			foreach($folderItems as $itemId=>$item) {

				if($folder['contains'] == 'video') {
					$itemObj = PDESGetVideoById($itemId);
				}
				else {
					$itemObj = PDESGetImageById($itemId);
				}

				if(!$itemObj) {
					continue;
				}

				$folderItem['item_id'] = $itemId;
				$folderItem['time'] = $itemObj['modified_at']; // Get time of specific item
				$folderItem['rank'] = $item['rank'];
				$folderItem['title'] = $this->getValueByLanguagePriority($itemObj, 'title');
				$folderItem['title_chinese'] = $itemObj['title_chinese'];
				$folderItem['title_english'] = $itemObj['title_english'];
				$folderItem['description'] = $this->getValueByLanguagePriority($itemObj, 'description');
				$folderItem['description_chinese'] = $itemObj['description_chinese'];
				$folderItem['description_english'] = $itemObj['description_english'];
				
				$items[] = $folderItem;
			}

			$folder['items']= $items;
			$newFolders[$k] = $folder;

		}

		return $newFolders;
	}

	public function getCategoryForPublish($catId) {
		$category = PDESGetCategoryById($catId);

		if($category === FALSE){
			return FALSE;
		}

		$categoryNew = array(
			'id'=>$catId,
			'parent_id'=>$category['parent_id'],
			'name'=>$category['title'],
			'forum_id'=>$category['forum_id'],
			'path' => $category['path'],
		);
	}

	public function getProgrammeCategoriesForPublish($programmeId) {
		$programme = PDESGetProgrammeById($programmeId);
		$categories = PDESGetProgrammeCategoriesByProgrammeId($programmeId);

		$programmeCategories = array();
		foreach($categories as $id=>$category){
			$categoryNew['category_path'] = $category['path'];
			$categoryNew['programme_path'] = $programme['path'];
			$categoryNew['programme_id'] = $programmeId;
			$categoryNew['parent_id'] = NULL;
			$categoryNew['forum_id'] = $category['forum_id'];
			$categoryNew['category_id'] = NULL;
			$categoryNew['category_id_0'] = $category['parent_id'];
			$categoryNew['category_id_1'] = $id;
			$categoryNew['rank'] = $category['rank'];
			$programmeCategories[] = $categoryNew;
		}
		return $programmeCategories;
	}
	
	public function getProgrammeChannelsForPublish($programmeId) {
		$channels = PDESGetProgrammeChannelsByProgrammeId($programmeId);

		$programmeChannels = array();
		foreach($channels as $channel){
			if ( (empty($channel['first_episode_time_onair'])) || ($channel['first_episode_time_onair'] == '0000-00-00 00:00:00') ) {
				$channel['first_episode_time_onair'] = '1970-01-01 00:00:00';
			}

			if ( (empty($channel['last_episode_time_onair'])) || ($channel['last_episode_time_onair'] == '0000-00-00 00:00:00') ) {
				$channel['last_episode_time_onair'] = '2029-12-31 23:59:59';
			}
			$programmeChannels[] = $channel;
		}
		return $programmeChannels;
	}

	public function publishProgramme($programmeId, $userId) {
		$programmeData = $this->getProgrammeForPublish($programmeId);

		$catId = $programmeData['primary_category_id'];
		$data = array();

		$programmeCategories = $this->getProgrammeCategoriesForPublish($programmeId);
		$programmeChannels = $this->getProgrammeChannelsForPublish($programmeId);

		array_push($data,array('type'=>'Programme','data'=>$programmeData));
		foreach($programmeCategories as $category) {
			array_push($data,array('type'=>'ProgrammeCategory','data'=>$category));
		}
		foreach($programmeChannels as $channel) {
			array_push($data,array('type'=>'ProgrammeChannel','data'=>$channel));
		}

		if ( isset($programmeData['folders']) && is_array($programmeData['folders']) ) {
			$folders = $programmeData['folders'];
			$filledFolders = $folders;

			foreach($folders as $folderType=>$folder) {
				if($folder['contains'] == 'video' && isset($filledFolders[$folderType])) {
					foreach($filledFolders[$folderType]['items'] as $item) {
						$retryTime = time();
						$passed = FALSE;
						$retryCount = 0;

						$video = $this->getVideoForPublish($item['item_id']);

						if($video !== FALSE) {
							array_push($data,array('type'=>'FolderItem','data'=>$item));
							$folder_data = $this->genFolderDataByFolderItemData($item);
							array_push($data,array('type'=>'Folder','data'=>$folder_data));
							array_push($data,array('type'=>'Video','data'=>$video));							
							$folder_item_video_data = $this->genFolderItemVideoDataByFolderItemDataAndVideoData($item, $video);
							array_push($data,array('type'=>'FolderItemVideo','data'=>$folder_item_video_data));
						}
						else {
							error_log('Could not publish video '.$item['item_id']);
							return -1;
						}
					}
				}
				
				if($folder['contains'] == 'image' && isset($filledFolders[$folderType])) {
					foreach($filledFolders[$folderType]['items'] as $item) {
						$image = $this->getImageForPublish($item['item_id'],$item['folder_type']);
						
						if ($image !== FALSE) {
							array_push($data,array('type'=>'FolderItem','data'=>$item));
							$folder_data = $this->genFolderDataByFolderItemData($item);
							array_push($data,array('type'=>'Folder','data'=>$folder_data));							
							
							array_push($data,array('type'=>'Image','data'=>$image));
							$folder_item_image_data = $this->genFolderItemImageDataByFolderItemDataAndImageData($item, $image);
							array_push($data,array('type'=>'FolderItemImage','data'=>$folder_item_image_data));
						}
						else {
							error_log('Could not publish image '.$item['item_id']);
							return -2;
						}
					}
				}
			}
		}
		return $data;
	}

	public function publishCast($castId, $userId) {
		$castData = $this->getCastForPublish($castId);
		$folders = (isset($castData['folders']) && is_array($castData['folders'])) ? $castData['folders'] : array();
		$data = array(
			array(
				'type' => 'Personage',
				'data' => $castData
			),
		);

		foreach ($folders as $folder) {
			# removed by vanni
			#if ( ($folder['type'] == 'head_photo') || ($folder['type'] == 'full_photo') ) {
				foreach($folder['items'] as $item) {
					$image = $this->getImageForPublish($item['item_id'],$folder['type']);
				
					if($image !== FALSE) {
						array_push($data,array('type' => 'FolderItem', 'data' => $item));
						$folder_data = $this->genFolderDataByFolderItemData($item);
						array_push($data,array('type'=>'Folder','data'=>$folder_data));
						
						array_push($data,array('type'=>'Image','data'=>$image));
						$folder_item_image_data = $this->genFolderItemImageDataByFolderItemDataAndImageData($item, $image);
						array_push($data,array('type'=>'FolderItemImage','data'=>$folder_item_image_data));						
					}
				}
			# removed by vanni	
			#}
		}

		return $data;
	}

	public function publishEpisode($episodeId, $userId) {
		$episodeData = $this->getEpisodeForPublish($episodeId);
		unset($episodeData['status']);

		$data = array();
		array_push($data,array('type'=>'Episode','data'=>$episodeData));

		if ( isset($episodeData['folders']) && is_array($episodeData['folders']) ) {
			$folders = $episodeData['folders'];
			$filledFolders = $folders;
			foreach($folders as $folderType=>$folder) {
				if($folder['contains'] == 'image' && isset($filledFolders[$folderType])) {
					foreach($filledFolders[$folderType]['items'] as $item) {

						$image = $this->getImageForPublish($item['item_id'],$item['folder_type']);

						if($image !== FALSE) {
							array_push($data,array('type'=>'FolderItem','data'=>$item));
							$folder_data = $this->genFolderDataByFolderItemData($item);
							array_push($data,array('type'=>'Folder','data'=>$folder_data));
							
							array_push($data,array('type'=>'Image','data'=>$image));
							$folder_item_image_data = $this->genFolderItemImageDataByFolderItemDataAndImageData($item, $image);
							array_push($data,array('type'=>'FolderItemImage','data'=>$folder_item_image_data));
						}
						else {
							error_log('Could not publish image '.$item['item_id']);
							return -2;
						}
					}
				}
			}
		}

		$infos = PDESGetInfoListByEpisodeId($episodeId);
		if(count($infos) > 0) {
			foreach($infos as $type=>$infoList) {
				switch($type) {
					case 'general_info':
						$func = 'getInfoGeneralForPublish';
						break;
					case 'qa':
						$func = 'getInfoQAForPublish';
						break;
					default:
						$func = 'getInfo'.ucfirst($type).'ForPublish';
				}
				foreach($infoList as $infoId=>$info) {
					$infoData = $this->$func($infoId);
					array_push($data,array('type'=>'Info','data'=>$infoData));
				}
			}
		}

		return $data;
	}

	public function publishChapter($chapterId, $userId) {
		$chapterData = $this->getChapterForPublish($chapterId);
		$data = array();
		array_push($data,array('type'=>'Chapter','data'=>$chapterData));

		return $data;
	}

	public function publishCompleteProgramme($programmeId, $userId) {
		echo date('Y-m-d H:i:s')." -- Programme: $programmeId\n";
		$start_time = microtime(true) ;
		$allData    = array('delete'=>array(), 'update'=>array());
		$programme  = PDESGetProgrammeById($programmeId);

		if ($programme === FALSE || !isset($programme['status']) || ($programme['status'] != 1)) {
			### Only send programme ID for deletion.
			$allData = array(
				'delete' => array(array(
					'type'=>'Programme',
					'keys'=>array('id'=>$programmeId)
				))
			);
		}elseif($programme <= 0) {
			echo "Some errors were encountered for $programmeId. \n";
			return TRUE;
		}else{

			$update_data = array();
			$data = $this->publishProgramme($programmeId, $userId);
			$update_data = array_merge($update_data, $data);

			$episodeList = PDESGetEpisodeListByProgrammeId($programmeId);
			foreach ($episodeList as $episode) {
				$data = $this->publishEpisode($episode['id'], $userId);
				$update_data = array_merge($update_data, $data);
			}

			$personageList = PDESGetCastListByProgrammeId($programmeId);
			foreach ($personageList as $personage) {
				//error_log("\tPersonage: {$personage['id']}");
				$data = $this->publishCast($personage['id'], $userId);
				$update_data = array_merge($update_data, $data);
			}


			$videoList = PDESGetVideoListByProgrammeId($programmeId);
			foreach ($videoList as $video) {
				$chapterMarkingList = PDESGetChapterListByVideoId($video['id']);
				foreach ($chapterMarkingList as $chapterMarking) {
					$data = $this->publishChapter($chapterMarking['id'], $userId);
					$update_data = array_merge($update_data, $data);
				}
			}
			$allData['update'] = $update_data;
		}
		$end_time = microtime(true) ;
		$count = count($allData['update']) + count($allData['delete']);
		echo "Sending $count items time:(".round(($end_time - $start_time), 5).")\n";
		return $allData;
	}
}
?>
